<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\Services\ClientUserService;
use App\Services\RoomManager;
use Hyperf\Di\Annotation\Inject;
use Hyperf\WebSocketServer\Sender;

class IndexController extends AbstractController
{
    /**
     * @Inject
     * @var Sender
     */
    protected $sender;

    protected $clientUserService;

    protected $roomManager;

    public function __construct()
    {
        $this->clientUserService = ClientUserService::getInstance();
        $this->roomManager = RoomManager::getIns();
    }

    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();

        $this->pushAll();
        $this->pushOne('1001');
        return [
            'method' => $method,
            'message' => "Hello {$user}.",
            'room_players' => $this->getRoomPlayers('room_01'),
        ];
    }

    protected function getAllFds()
    {
        return $this->clientUserService->getAllFds();
    }

    protected function pushAll()
    {
        $allFds = $this->getAllFds();
        array_walk($allFds, function ($fd) {
            go(function () use ($fd) {
                $this->sender->push($fd, json_encode(['message' => sprintf('hello, fd %s', $fd)]));
            });
        });
    }

    protected function pushOne($userId)
    {
        $fd = $this->clientUserService->getFdByUserId($userId);
        $this->sender->push((int) $fd, json_encode(['message' => sprintf('hello, user %s', $userId)]));
    }

    protected function pushInRoom($roomId)
    {
    }

    protected function getRoomPlayers($roomId)
    {
        return $this->roomManager->getRoomPlayer($roomId);
    }
}
